package com.zfk.framework.variable_handling;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zfk.framework.variable_handling.GlobalVariablePool.getFromVariablePool;

public class VariableReplace {
    public static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{\\{(\\w+)\\}\\}");

    /**
     * 替换caseData String字段的变量占位符
     * @param input，需要替换的String字段
     * @return 替换后的String字段
     */
    public static String replaceVariables(String input) {
        if (input == null) {
            return null;
        }
        Matcher matcher = VARIABLE_PATTERN.matcher(input);
        String result = input;
        while (matcher.find()) {
            String variableName = matcher.group(1);
            //从变量池中获取变量值
            Object variableValue = getFromVariablePool(variableName);
            if (variableValue != null) {
                //替换变量
                result = result.replace("{{" + variableName + "}}", variableValue.toString());
            }
        }
        return result;
    }
    //替换 Map字段中的 {{variable}}

    /**
     * Case Data中的Map字段中的 {{variable}}
     * @param inputMap Case Data中的Map字段，
     * @return 替换后的Map字段
     */
    public static Map<String, Object> replaceVariablesInMap(Map<String, Object> inputMap) {
        if (inputMap == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        //遍历Map字段
        for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String) {
                resultMap.put(key, replaceVariables((String) value));
            } else {
                resultMap.put(key, value);
            }
        }
        return resultMap;
    }
}
